const routes = require('../routes/routes');
const sessionMgr = require('./sessionMgr');
require('../routes/login');
require('../routes/common');
require('../routes/index');
require('../routes/player');

let routesHandle = (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    let method = req.method;
    if (method !== 'POST') {
        res.send({
            err: 104
        });
        return
    }
    let msg = req.body;
    let url = req.path.substr(1);
    console.log(req.path, msg);
    let notLoginRoute = routes.notLogin[url];
    if (notLoginRoute) {
        notLoginRoute(msg, (err, data) => {
            res.send({
                err: err,
                data: data
            });
        });
        return;
    }
    let session = sessionMgr.get(req.query.sid);
    if (!session) {
        res.send({
            err: 105
        });
        return
    }
    let userLoginRoute = routes.userLogin[url];
    if (userLoginRoute) {
        userLoginRoute(session, msg, (err, data) => {
            res.send({
                err: err,
                data: data
            });
        });
        return;
    }

    let loginRoute = routes.login[url];
    if (loginRoute) {
        if (!session.player) {
            res.send({
                err: 106
            });
            return
        }
        loginRoute(session, msg, (err, data) => {
            res.send({
                err: err,
                data: data
            });
        });
        return;
    }

    res.send({
        err: 103,
        data: {
            url: req.path,
            routes: routes
        }
    });

};

module.exports = routesHandle;